import java.text.DecimalFormat;
import java.text.NumberFormat;

/*
 * class Scale
 */

public class Scale {
	
	public Scale(IPowerControl powerCtrl, IDisplay display, ISoundDevice soundDevice, int autoShutdownTimeMs)
	{
		this.itsIPowerControl 		= powerCtrl;
		this.itsIDisplay 			= display;
		this.itsISoundDevice		= soundDevice;
		this.itsIWeighable			= new Weighable(0.0);
		this.itsTare				= new Weighable(0.0);
		this.itsPowerControlTrigger	= new PowerControlTrigger(autoShutdownTimeMs, itsIPowerControl);
	}
	
	public void weigh(IWeighable weighable)
	{
		itsIWeighable = weighable;
		// the net weight is always the current weight - tare weight
		double netWeight = itsIWeighable.getWeight() - itsTare.getWeight();
		String weightStr = calcFormattedWeight(netWeight);
		itsIDisplay.display(weightStr);
		if(playBeep)
		{
			itsISoundDevice.beep();
		}
		// restart auto shut off
		itsPowerControlTrigger.start();
	}
	
	/*
	 * getFormattedWeight
	 * convert grams to the proper output string, calculating the conversion
	 */
	private String calcFormattedWeight(double weightGrams)
	{
		String retval = new String();
		
		if(units == WeightUnits.GRAMS)
		{
			NumberFormat gramFormatter = new DecimalFormat("#0.000");
			retval = gramFormatter.format(weightGrams) + " grams";
		}
		else if(units == WeightUnits.POUNDS)
		{
			double gramsToPoundsFactor = 0.00220462262;
			double weightPounds = weightGrams * gramsToPoundsFactor;
			
			int poundsOnly = (int)Math.floor(weightPounds);
			double ounces = (weightPounds - poundsOnly)/16;
			NumberFormat ounceFormatter = new DecimalFormat("#0.00");	
			retval = Integer.toString(poundsOnly) + " lb " + ounceFormatter.format(ounces) + " oz";
		}
		return retval;
	}
	
	public void setTare()
	{
		itsTare = itsIWeighable;
		// restart auto shut off
		itsPowerControlTrigger.start();
	}
	
	public void setUnits(WeightUnits units)
	{
		this.units = units;
		weigh(itsIWeighable);
	}
	
	public void beepOn()
	{
		playBeep = true;
		// restart auto shut off
		itsPowerControlTrigger.start();
	}
	
	public void beepOff()
	{
		playBeep = false;
		// restart auto shut off
		itsPowerControlTrigger.start();
	}

	
	private IPowerControl 		itsIPowerControl;
	private IDisplay			itsIDisplay;
	private ISoundDevice		itsISoundDevice;
	private IWeighable			itsIWeighable;
	private IWeighable			itsTare;
	private PowerControlTrigger	itsPowerControlTrigger;
	private int					waitUntilShutOffMs = 2000;
	private boolean				playBeep = true;
	private WeightUnits			units = WeightUnits.GRAMS;
}


